×
☰ See All Chapters

Java BiConsumer Functional Interface

BiConsumer is the java provided functional interface to consume the values and perform the desired operation on the values. Bi means two, BiConsumer works on two values.

Writing an application involves comparing, computing and consuming values. Assume, inside a method say myMeth(), if we have to execute same code multiple time then we have to duplicate the code. To avoid this we can create some utility class and create the method to execute repeated code and call this method inside our method myMeth() any number of times. This is good solution if the common method we wrote is used across the application many times. If we call this utility method only few times inside one particular method, writing a utility class and a utility method is again a bad solution, because, this utility method is sure to be called only few times and that too only when the myMeth()is called. The next solution is to write some functional interface with a method taking desired number of parameters and perform desired operation. So now, we can use this functional interface with lambda expression and we can execute any logic and use it any times.

BiConsumer is the java provided functional interface with two parameters and we do not need to create the functional interface to consume the values. Just write the logic using lambda expression and use it.

BiConsumer Method signature

BiConsumer functional method has two parameters and does not return any value.

@FunctionalInterface

public interface BiConsumer<T, U> {

 

    /**

     * Performs this operation on the given arguments.

     *

     * @param t the first input argument

     * @param u the second input argument

     */

    void accept(T t, U u);

… …

… …

}

BiConsumer Example

package com.java4coding;

 

import java.util.HashMap;

import java.util.Map;

import java.util.function.BiConsumer;

 

public class BiConsumerExample {

 

        public static void main(String args[]) {

 

                Map<String, Integer> map = new HashMap<>();

                map.put("Manu", 100);

                map.put("Advith", 101);

                map.put("Tyagraj", 102);

                BiConsumer<String, Integer> biConsumer = (name, id) -> System.out.println("Name: " + name + " ID: " + id);

                map.forEach(biConsumer);

        }

}

Output:

Name: Advith ID: 101

Name: Tyagraj ID: 102

Name: Manu ID: 100

 


All Chapters
Author